﻿package com.cilico.single.view;

import java.util.Vector;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.ViewFlipper;
import com.cilico.single.ConfigManager;
import com.cilico.single.Mid;
import com.cilico.single.R;
import com.cilico.single.components.Alert;
import com.cilico.single.components.ChannelRepository.ChannelErrorException;
import com.cilico.single.components.ImageItem;
import com.cilico.single.components.TabItem;
import com.cilico.single.shopcart.ShopCart;
import com.cilico.single.utils.Constant;
import com.cilico.single.utils.ConstantRepository;
import com.cilico.single.utils.HttpManager.EmptyResultException;
import com.cilico.single.utils.Utils;

public class MainView extends BaseView implements OnGestureListener{
	static int gridcount=0; //总页数
	static int currentPageIndex_ = 0 ; // 当前页数
	TextView tv_; // 点，用于换页
	int colNum_; // 一行图标的总数
	int iconW_; // icon宽
	int channlIndex_;
 	static String temploginStatus_ = "0";
	Vector<String> menuV_;// add inherent channels
	Vector<String>[] subMenuV_;
	ImageItem backItem_;
	Bitmap customFocusImg_;
	static Bitmap otherPageImg_ = null;
	static Bitmap currentPageImg_ = null;
	int columnWidth_; // 表格列宽
	private long systemTime_=0;
	private ViewFlipper flipper;
	private GestureDetector detector;
	int llUpheight_;
	int itemheight_;
	int llDownheight_; // 底部进入登陆按钮高度
	int screenheight_;
	

	@SuppressWarnings("unchecked")
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		activities_.add(this);
		detector = new GestureDetector(this);
		flipper = new ViewFlipper(this);
		
		Bitmap icon = ConstantRepository.decodeBitmap(getResources(), R.drawable.naviitem1);
		iconW_ = icon.getWidth() + Utils.getScaledValue(5);
		icon.isRecycled();
		icon = null;
		
		Paint p1 = new Paint();
		p1.setTextSize(Utils.getScaledValue(ConfigManager.SIZE_MAIN));
		itemheight_ = (int) (iconW_ + p1.getTextSize());
		screenheight_ = Utils.screenHeight_;
		Bitmap backgroundImg_ = ConstantRepository.decodeBitmap(this.getResources(), R.drawable.t_bar);
		llUpheight_ = backgroundImg_.getHeight();
		llDownheight_ = 20;
		tv_ = new TV(this);
		tv_.setTextColor(0xff000000);
		tv_.setGravity(Gravity.CENTER_HORIZONTAL);
		if (null != mid_){
			if(mid_.um_.loginStatus_!=null&&mid_.um_.loginStatus_.equals("0")){
				tv_.setLayoutParams(new LinearLayout.LayoutParams(Utils.screenWidth_, 15,1));
			} else{
				tv_.setLayoutParams(new LinearLayout.LayoutParams(Utils.screenWidth_, 20,1));
			}
		}
	
		// 得到其他界面传递过来的值
		Bundle bundle = getIntent().getExtras();
		boolean isShowMessage = false;
		if (null != bundle) {
			isShowMessage = bundle.getBoolean("isShowMessage");
		}
		// 进入界面后立即复制当前界面对象，保存当前界面
		ConfigManager.currentView_ = this;
		// 添加菜单
		try {
			addMainViewMenu();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		initScreenManager(this);// 初始化界面布局
		// 设置背景图片
		setBackgroundResource(R.drawable.background, this);
		// 添加标题栏控件
		addTitleBar();
		addTitleBarButton();
		titleBar_.resetTitleBarContent(1, null, null, "exit");
		menuV_ = mid_.um_.menuV_;// 退出等菜单
		int size=0;
		if (menuV_ != null)
			size = menuV_.size();
		final int size_1 = 4*((screenheight_-llUpheight_-llDownheight_)/(itemheight_ + 5));
		if((size%size_1)==0){
		    gridcount = size/size_1;
		} else {
			gridcount = (size/size_1)+1;
		}
		if(tv_!=null && gridcount >1 ){
        	llDown_.addView(tv_);
        }
		if (mainMenuMap_ == null) {
			int lenght = ConfigManager.mainMenuShortCut_.length;
			mainMenuMap_ = new Bitmap[lenght];
			for (int i = lenght - 1; i >= 0; i--) {
				mainMenuMap_[i] = mid_.constant_.getChannelIcon(ConfigManager.mainMenuShortCut_[i]);
			}
		}
//		setGridView(size,size_1);
		addTextViewLayout(size,size_1);
		if(mid_.um_.loginStatus_!=null){
			//从免登录进入登录后九宫格时将currentPageIndex_置0
			//（防止从免登录第二页切换登录成功后的初始化的九宫格显示的不是第一页的情况）
			if (mid_.um_.loginStatus_.equals("1") && temploginStatus_.equals("0")){
				temploginStatus_ = "1";
				currentPageIndex_ = 0;
			}
		}
		for (int cpi = 0; cpi < currentPageIndex_; cpi ++) {
			flipper.showNext();
		}
		
        tabBar_.addContentChild(flipper);
		show();
		// 将中间布局管理器布局方式设置为靠上
		tabBar_.setGravity(Gravity.TOP);
		tabBar_.setContentLayoutGravity();
//		if (isShowMessage && mid_.um_.loginStatus_ != null && ((mid_.um_.loginStatus_.equals("0")) || (Utils.userIsNotFirstLogin_ && mid_.um_.loginStatus_.equals("1"))))
//				Utils.showLoginMessage(mid_, this);
		if (mid_.um_.versionNumToInt(mid_.um_.versionNum_) > 
				mid_.um_.versionNumToInt(mid_.midletVersion_)) {
			showDialog("有新版本，您要升级吗？");
		}
	}
	
	private void showDialog(String msg) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("注意");
		builder.setMessage(msg);
		builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				mid_.um_.updateVersion(MainView.this);
			}
		});
		builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				mid_.um_.versionNum_ = "0.0.0";//取消更新的之后，进入宫格按返回键会再次弹出提示更新
			}
		});
		builder.show();
	}

	private void addTitleBarButton() {
		if (null != this.titleBar_) {
			this.titleBar_.showHeader_ = true;
			this.titleBar_.setHpText(this.getString(R.string.menuExit));
		}
	}

	/**
	 * 当屏幕横竖切换时调用此方法
	 * */
	public void onConfigurationChanged(Configuration newConfig) {
		llUp_.removeAllViews();
		int roientation = this.getResources().getConfiguration().orientation;
		// 横竖屏切换时调用此方法交换宽高
		changeScreenWidthHeight(roientation);
		super.onConfigurationChanged(newConfig);
	}

	// 按键操作
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		switch (keyCode) {
		case KeyEvent.KEYCODE_BACK:
			keyBackPressed();
			break;
		default:
			return super.onKeyDown(keyCode, event);
		}
		return true;
	}

	/**
	 * When we go back we should re-set current item to be the current channel.
	 */
	public void keyBackPressed() {
		// 点击退出菜单命令
		Alert.exitSystem(this);
	}

	protected void addMainViewMenu() {
		setRightMenuMode(BaseView.OPTIONS_MENU, null);
		setLeftMenuMode(BaseView.EXIT_MENU);
	}

	void show() {
		initView();
	}

	void initView() {
		try {
			populate();
		} catch (ChannelErrorException ex) {
			if (ex.getMessage().startsWith("Access denied")) {
				try {
					mid_.um_.resetLoginAndKeys();
				} catch (Exception ex2) {
					mid_.alert(this, getString(R.string.loginAgain), false);
					return;
				}
				mid_.gotoLoginView(this);
			} else {
				mid_.alert(this, ex.getMessage(), true);
			}
			return;
		} catch (EmptyResultException ex) {
			// appendChannelElememt(ex.getMessage(), null);
		} catch (Exception ex1) {
			Utils.printOutToConsole("MainView-initView-ex1:" + ex1.toString());
			mid_.alert(this, ex1.toString(), true);
			return;
		}
	}

	void populate() throws Exception {
		show(this);
	}


	/**
	 * 从九宫格进入下一页面
	 * Enter the view below main view. It's maybe a detail view with a tab, or an account list view without a tab.
	 */
	private void stepIntoView(String mainChannelID, String subChannelID) {
		ShopCart.clearData();
		 // 当前图标若指向collection,它将会获取频道列表；若指向channel，它将会获取POI列表(poi list).
		Channel mainChannel = mid_.channelRepo_.getChannel(mainChannelID); // 获取当前频道
		mid_.channelEntity_.gotoDetailViewFromMainView(subChannelID, this, Mid.DETAIL_VIEW, mainChannel.id(), mainChannel.title());
	}

	private void setBackgroundResource(int resourceId, MainView context) {
		super.setBackgroundResource(resourceId, context, 2);
	}
	
	/**
	 * 获取字符串在数组中的下标
	 * */
	private int getIndex (String str) {
		for (int i = ConfigManager.mainMenuShortCut_.length - 1; i >= 0; i--) {
			if (str.contains(ConfigManager.mainMenuShortCut_[i])) {
				return i; 
			}
		}
		return 0;
	}
	
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		return this.detector.onTouchEvent(event);
	}

	@Override
	public boolean onDown(MotionEvent e) {
		return false;
	}

	@Override
	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
			float velocityY) {
		if (e1.getX() - e2.getX() > 60) {
			if(currentPageIndex_<gridcount-1){
				flipper.setInAnimation(AnimationUtils.loadAnimation(this, R.anim.push_left_in1));
				flipper.setOutAnimation(AnimationUtils.loadAnimation(this, R.anim.push_left_out1));
				flipper.showNext();
				currentPageIndex_++;
				tv_.invalidate();
			}
			return true;
		} else if (e1.getX() - e2.getX() < -60) {
			if(currentPageIndex_>0){
				flipper.setInAnimation(AnimationUtils.loadAnimation(this, R.anim.push_right_in1));
				flipper.setOutAnimation(AnimationUtils.loadAnimation(this, R.anim.push_right_out1));
				flipper.showPrevious();
				currentPageIndex_--;
				tv_.invalidate();
			}
			return true;
		}
		return false;
	}

	@Override
	public void onLongPress(MotionEvent e) {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
		return false;
	}

	@Override
	public void onShowPress(MotionEvent e) {

	}

	@Override
	public boolean onSingleTapUp(MotionEvent e) {
		return false;
	}

	public void onDestory() {
		activities_.remove(this); // 把当前Activity从集合中移除
	}
	
	
	public class AppsAdapter extends BaseAdapter {
		 
		Vector<String> mVector;

		public AppsAdapter() {
			if (mVector == null) {
				mVector = new Vector<String>();
			} else {
				mVector.removeAllElements();	
			}
		}
		
		public AppsAdapter(Vector<String> subMenuV) {
			mVector = subMenuV;
			if(mVector == null) {
				mVector = new Vector<String>();
			}
		}
		
		
		public View getView(int i, View convertView, ViewGroup parent) {
			ImageItem item = null;
			String shortCut = (String) mVector.elementAt(i);
			Channel ch = mid_.channelRepo_.getChannelByShortCut(shortCut);
			int index = getIndex(ch.shortCut_);
			int showNew = ch.showNew_;
			if (ch != null) {
				Bitmap mainIcon = mainMenuMap_[index];
				item = new ImageItem(MainView.this, mainIcon,showNew);
				item.setScaleType(ImageView.ScaleType.FIT_CENTER);
				item.setLayoutParams(new GridView.LayoutParams(50, 50));
				item.attrValue_ = ch.id();
				item.setDescriptionText(mid_.constant_.fitText(ch.title()));
				Paint p = new Paint();
				p.setTextSize(Utils.getScaledValue(ConfigManager.SIZE_MAIN));
				int w = (int) p.measureText(getString(R.string.measureText));
				item.width_ = iconW_ > w ? iconW_ : w;
				item.height_ = (int) (iconW_ + p.getTextSize());
			}
			return item;
		}

		public final int getCount() {
			// 取得列表单元的大小
			if (null != mVector)
				return mVector.size();
			else
				return 0;
		}

		public final Object getItem(int position) {
			// 取得列表元素
			return mVector.elementAt(position);
		}

		public final long getItemId(int position) {
			return position;
		}
	}

	static final class TV extends TextView {

		public TV(Context context) {
			super(context);
			if (otherPageImg_ == null) {
				otherPageImg_ =ConstantRepository.decodeBitmap(this.getResources(), R.drawable.grayspot);
			}
			if (currentPageImg_ == null) {
				currentPageImg_ =ConstantRepository.decodeBitmap(this.getResources(), R.drawable.lightspot);
			}
		}
		 protected void onDraw(Canvas canvas) {
				Paint paint_ = new Paint();
				int x ;
				if((gridcount%2)==0){
					x = Utils.screenWidth_/2 - (gridcount/2)*20+10;
				} else{
					x = Utils.screenWidth_/2 - (gridcount/2)*20;
				}
				for(int i=0;i<gridcount;i++){
					if(currentPageIndex_==i){
						canvas.drawBitmap(currentPageImg_, x+20*i, 0, paint_);
					} else{
						canvas.drawBitmap(otherPageImg_, x+20*i, 0, paint_);
					}
				}
				try {
					super.onDraw(canvas);
				} catch (java.lang.StackOverflowError se) {
					invalidate();
					se.printStackTrace();
				}
		 }
		
	}
	private void addTextViewLayout(int size,int size_1){
		LinearLayout liLayout = null;
		String shortCut;
		Channel ch;
		liLayout = new LinearLayout(this);
		LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
				Utils.screenWidth_, LinearLayout.LayoutParams.WRAP_CONTENT);
		liLayout.setOrientation(LinearLayout.VERTICAL);
		liLayout.setLayoutParams(params);
		int kk = 0;
		for (int i = 0; i < gridcount; i++) {
			for (int j = 0; j < 2;j++) {
				if (j == 1) {
					kk = ++j;
				}
				LinearLayout liLayout2 = new LinearLayout(this);
				LinearLayout.LayoutParams params2 = new LinearLayout.LayoutParams(
						Utils.screenWidth_, LinearLayout.LayoutParams.WRAP_CONTENT);
				liLayout2.setOrientation(LinearLayout.HORIZONTAL);
				liLayout2.setLayoutParams(params2);
				
				shortCut = (String) menuV_.elementAt(kk);
				ch = mid_.channelRepo_.getChannelByShortCut(shortCut);
				int index1 = getIndex(ch.shortCut_);
				Bitmap bp1 = Utils.scalBitmap(mainMenuMap_[index1]); 
				TextView tView1 = new TextView(this);
				tView1.setBackgroundColor(Color.WHITE);
				tView1.setBackgroundDrawable(new BitmapDrawable(bp1));
				tView1.setOnClickListener(new ClickTextView(kk, ch));
				liLayout2.addView(tView1);
				
				shortCut = (String) menuV_.elementAt(kk+1);
				ch = mid_.channelRepo_.getChannelByShortCut(shortCut);
				int index2 = getIndex(ch.shortCut_);
				Bitmap bp2 = Utils.scalBitmap(mainMenuMap_[index2]); 
				TextView tView2 = new TextView(this);
				tView2.setBackgroundColor(Color.WHITE);
				tView2.setBackgroundDrawable(new BitmapDrawable(bp2));
				tView2.setOnClickListener(new ClickTextView(kk+1, ch));
				liLayout2.addView(tView2);
				
				liLayout.addView(liLayout2);
			}
			flipper.addView(liLayout);
		}
	}
	
	class ClickTextView implements OnClickListener{

		int pos;
		Channel  channel;
		ClickTextView(int position,Channel  channel){
			pos = position + 1;
			this.channel = channel;
		}
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			systemTime_ = System.currentTimeMillis() - systemTime_;
			ConfigManager.STATUSBAR_INDEX = pos;
			TabItem.currentTab_ = pos ;
			TabItem.saveCurrentTab_ = TabItem.currentTab_;
			channlIndex_ = pos;
			mid_.removeDisplayable();
			if (mid_.poiRepo_ != null)
				mid_.poiRepo_.removeAllActionPoi();// 清栈
			mid_.pushDisplayable(Mid.MAIN_VIEW, null, Constant.MAIN_TITLE);

			if (systemTime_ > 1000) {
				mid_.channelRepo_.setCurrentChannelID(channel.id());
				stepIntoView(channel.id(), null);
			}
		}
		
	}
	
	private void setGridView(int size,final int size_1){
		// 初始化界面表格对象
		GridView[] screenGrid_ = new GridView[gridcount];
		subMenuV_ =new Vector[gridcount];
		for(int i=0;i<gridcount;i++){
			if (subMenuV_[i] == null) {
				subMenuV_[i] = new Vector<String>();
			}
			if (i < gridcount - 1) {
				for (int j = 0; j < size_1; j++) {
					subMenuV_[i].add(menuV_.elementAt(i * size_1 + j));
				}
			} else {
				for (int j = (gridcount - 1) * size_1; j < size; j++) {
					subMenuV_[i].add(menuV_.elementAt(j));
				}
			}
			screenGrid_[i] = new GridView(this);
//			screenGrid_[i].setBackgroundColor(Color.RED);
			screenGrid_[i].setAdapter(new AppsAdapter(subMenuV_[i]));
			// screenGrid_[i].setAdapter(new AppsAdapter());
			// 设置行列为自适应效果
//					screenGrid_[i].setNumColumns(GridView.AUTO_FIT);
			screenGrid_[i].setNumColumns(colNum_);
			// 设置列宽
			Paint p = new Paint();
			p.setTextSize(Utils.getScaledValue(ConfigManager.SIZE_MAIN));
//					int columnWidth = Math.max(iconW_, (int) p.measureText(getString(R.string.measureText)));
			int columnWidth = Utils.screenWidth_ / colNum_ ;
			
			screenGrid_[i].setColumnWidth(columnWidth);
			// 设置伸张模式
			screenGrid_[i].setStretchMode(GridView.STRETCH_COLUMN_WIDTH);
			// 设置水平间距
//					int horizontalSpacing = (Utils.screenWidth_ - columnWidth * colNum_) / (colNum_ * 4);
//					if (horizontalSpacing > 0) {
				// 列间距（一列n个）
//						screenGrid_[i].setHorizontalSpacing(horizontalSpacing);
				screenGrid_[i].setHorizontalSpacing(5);
				// 行间距（一行n个）
				screenGrid_[i].setVerticalSpacing(5);
//					}
			screenGrid_[i].setPadding(5, 5, 5, 5);
			// 设置对齐方式为水平居中
			screenGrid_[i].setGravity(Gravity.CENTER_HORIZONTAL);
			// tabBar_.addContentChild(screenGrid_);
			screenGrid_[i].setOnTouchListener(new OnTouchListener() {
				@Override
				public boolean onTouch(View v, MotionEvent event) {
					return detector.onTouchEvent(event);
				}
			});

			// 设置表格控件点击响应
			screenGrid_[i].setOnItemClickListener(new OnItemClickListener() {
				public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
					// changeFocusImage(arg0, arg2);
					systemTime_ = System.currentTimeMillis() - systemTime_;
					ConfigManager.STATUSBAR_INDEX = arg2;
					TabItem.currentTab_ = arg2 + 1 + currentPageIndex_ * size_1;
					TabItem.saveCurrentTab_ = TabItem.currentTab_;
					channlIndex_ = arg2;
					mid_.removeDisplayable();
					if (mid_.poiRepo_ != null)
						mid_.poiRepo_.removeAllActionPoi();// 清栈
					mid_.pushDisplayable(Mid.MAIN_VIEW, null, Constant.MAIN_TITLE);
					ImageItem imgItem = (ImageItem) arg1;

					if (systemTime_ > 1000) {
						mid_.channelRepo_.setCurrentChannelID(imgItem.attrValue_);
						stepIntoView(imgItem.attrValue_, null);
					}
				}
			});

			flipper.addView(screenGrid_[i]);
		}
	}
}
